package com.main.by.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.main.by.entity.vo.NewsInfoVO;
import com.main.by.entity.vo.SubmitVO;
import com.main.by.entity.vo.TaskVO;
import com.main.by.exception.ServiceException;
import com.main.by.service.NewsInfoService;
import com.main.by.service.TaskService;
import com.main.by.service.UploadFileService;
import com.main.by.util.StringUtil;

/**
 * 后台管理用户登录
 * @author Wendel
 * 2016年1月18日
 */
@Controller
@RequestMapping("/customjsp/")
public class CustomInfoControll {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private NewsInfoService newSInfoService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private UploadFileService uploadFileService;
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request){
		logger.info("前台用户登录");
		return "customjsp/login";
	}
	
	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register(HttpServletRequest request){
		logger.info("前台用户登录");
		return "customjsp/register";
	}
	
	
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(HttpServletRequest request){
		logger.info("查看所有发布任务-------");
		try {
			List<TaskVO> taskInfo = taskService.findAllTask(request);
			request.getSession().setAttribute("customTaskInfList", taskInfo);
		}catch (ServiceException serviceE){
			return "customjsp/newsList";
		}catch (Exception e) {
			logger.error("select news failed! ", e);
			return "customjsp/newsList";
		}
		return "customjsp/index";
	}
	
	@RequestMapping(value = "task", method = RequestMethod.GET)
	public String task(HttpServletRequest request){
		String errorMessage = "修改失败";
		String taskId =  request.getParameter("taskId");
		int id = 0;
		if (StringUtil.isNotBlank(taskId)) {
			id = Integer.parseInt(taskId);
			logger.info("根据ID查找管理员信息-------");
			TaskVO taskInfo = new TaskVO();
			try {
				taskInfo = taskService.findTaskById(id);
				request.getSession().setAttribute("taskInfoById", taskInfo);
			}catch (ServiceException serviceE){
				errorMessage = serviceE.getMessage();
				return "customjsp/index";
			}catch (Exception e) {
				logger.error("select admin failed! ", e);
				return "customjsp/index";
			}
		} else {
			return "customjsp/index";
		}
		
		return "customjsp/task";
	}
	
	@RequestMapping(value = "taskContent", method = RequestMethod.GET)
	public String taskContent(HttpServletRequest request){
		logger.info("检查前台用户是否登录");
		if (request.getSession().getAttribute("customUser")==null) {
			return "customjsp/login";
		} else {
			return "customjsp/taskContent";
		}
		
	}
	
	@RequestMapping(value = "newsList", method = RequestMethod.GET)
	public String newsList(HttpServletRequest request){
		logger.info("查看所有新闻信息-------");
		try {
			List<NewsInfoVO> newInfo = newSInfoService.findAllNews(request);
			request.getSession().setAttribute("customNewsInfoList", newInfo);
		}catch (ServiceException serviceE){
			return "customjsp/index";
		}catch (Exception e) {
			logger.error("select news failed! ", e);
			return "customjsp/index";
		}
		return "customjsp/newsList";
	}
	
	@RequestMapping(value = "newsInfo", method = RequestMethod.GET)
	public String newsInfo(HttpServletRequest request){
		boolean flag = false;
		String errorMessage = "修改失败";
		String newsId =  request.getParameter("newsId");
		int id = 0;
		if (StringUtil.isNotBlank(newsId)) {
			id = Integer.parseInt(newsId);
		}
		logger.info("根据ID查找新闻-------");
		NewsInfoVO newsInfo = new NewsInfoVO();
		try {
			newsInfo = newSInfoService.findNewsById(id);
			request.getSession().setAttribute("customNewsInfo", newsInfo);
			flag = true;
		}catch (ServiceException serviceE){
			errorMessage = serviceE.getMessage();
			return "customjsp/newsList";
		}catch (Exception e) {
			logger.error("select news failed! ", e);
			return "customjsp/newsList";
		}
		return "customjsp/newsInfo";
	}
	
	
	@RequestMapping(value = "submitTask", method = RequestMethod.POST)
	@ResponseBody
	public void submitTask(HttpServletRequest request,HttpServletResponse response,@RequestParam("taskPic") MultipartFile file1) throws IOException{
		SubmitVO sumbitTaskInfo = new SubmitVO();
		PrintWriter out = response.getWriter();
		logger.info("taskUpload info:");
		boolean flag = false;
		//errorMessage：上传失败，则是错误信息；上传成功，则提示成功以及显示文件上传后的地址
		String errorMessage = "";  
		try{
			String destinationDir ="G:/byProject/byProject/webapp/submitUploadFile/";
			List<MultipartFile> file = new ArrayList<MultipartFile>();
			file.add(file1);
			String writeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			String qq = request.getParameter("qq");
			String telphone = request.getParameter("telphone");
			String zhifubao = request.getParameter("zhifubao");
			String bankcard = request.getParameter("bankcard");
			String weibo = request.getParameter("weibo");
			String qita = request.getParameter("qita");
			String taskId = request.getParameter("taskId");
			String userId = request.getParameter("userId");
			
			sumbitTaskInfo.setBankPay(bankcard);
			sumbitTaskInfo.setTelphone(telphone);
			sumbitTaskInfo.setUserQQ(qq);
			sumbitTaskInfo.setAliplay(zhifubao);
			sumbitTaskInfo.setBlog(weibo);
			sumbitTaskInfo.setInfo(qita);
			sumbitTaskInfo.setFlag("0");
			sumbitTaskInfo.setTaskId(taskId);
			sumbitTaskInfo.setUserId(userId);
			sumbitTaskInfo.setSubmitDate(writeDate);
			if (file.size() >= 1) {
				//获得文件的后缀名
				String file1Type = file.get(0).getContentType();
				String name1Type = file1Type.substring(file1Type.indexOf("/")+1,file1Type.length());
				if (("jpg".equals(name1Type) ||"bmp".equals(name1Type) || "gif".equals(name1Type) || "jpeg".equals(name1Type))){
					String fileName1Type = file.get(0).getOriginalFilename();
					String fileName1 = getFileName()+"1"+fileName1Type.substring(fileName1Type.indexOf("."),fileName1Type.length()); 
					sumbitTaskInfo.setTaskPic(fileName1);
					flag = uploadFileService.uploadHandoutImg(destinationDir,  file, fileName1,null);
					if (flag) {
						flag = taskService.addSubmitTaskInfo(sumbitTaskInfo, request, response);
					} else {
						//上传失败，返回到前台
						out
						.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
					}
					
				} else {
					out
					.print("<script type='text/javascript'>alert('不是标准的图片文件')</script>");
				}
			}
		}catch (ServiceException serviceE){
			logger.error("firstUpload failed!" , serviceE);
			errorMessage = serviceE.getMessage();
		}catch (Exception e){
			logger.error("firstUpload failed!" , e);
			errorMessage = "新增文件失败!";
		}
		if(flag){
		    //上传成功，返回到前台
			response.sendRedirect("submitSuccess");
		} else {
			//上传失败，返回到前台
			out
			.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
		}
	}
	
	@RequestMapping(value = "loginOut", method = RequestMethod.GET)
	public String loginOut(HttpServletRequest request){
		logger.info("用户退出登录");
		request.getSession().invalidate();
		return "customjsp/index";
	}
	
	private String getFileName() {
		//根据时间产生文件名
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssms");
		return df.format(new Date());
	}
}
